package com.example.springframeworklearning.converter;

import com.example.springframeworklearning.enums.OrderStatus;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * 二、通过配置 converter 来将 字符串转换为 枚举
 * @author luo
 * @since 2022/9/19 17:18
 */
@SuppressWarnings({"unchecked","cast"})
public class StringOrderStatusConverterFactory implements ConverterFactory<String, Enum> {

    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
//        简化处理，这里暂时只处理 OrderStatus 这一个枚举
        return new StringToEnumConverter<>();
    }

    public static final class StringToEnumConverter<T extends Enum> implements Converter<String, T> {

        @Override
        public T convert(String source) {
//            把字符串解析为对应的枚举
            return (T) (Enum.valueOf(OrderStatus.class, source.trim()));
        }
    }
}
